package com.free.rabbitmq.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.free.rabbitmq.common.mapper.MsgLogMapper;
import com.free.rabbitmq.common.model.MsgLog;
import com.free.rabbitmq.common.service.MsgLogService;
import com.free.rabbitmq.common.util.JodaTimeUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MsgLogServiceImpl extends ServiceImpl<MsgLogMapper, MsgLog> implements MsgLogService {

    @Override
    public MsgLog selectByMsgId(String msgId) {

        return baseMapper.selectById(msgId);
    }

    @Override
    public List<MsgLog> selectTimeoutMsg() {
        return baseMapper.selectList(
                new LambdaQueryWrapper<MsgLog>()
                        .eq(MsgLog::getStatus, 0)
                        .lt(MsgLog::getNextTryTime, new Date())
        );
    }

    @Override
    public boolean insertMsg(MsgLog msgLog) {

        return baseMapper.insert(msgLog) > 0;
    }

    @Override
    public boolean updateStatus(String msgId, Integer status) {
        MsgLog msgLog = new MsgLog();
        msgLog.setMsgId(msgId);
        msgLog.setStatus(status);
        return baseMapper.updateById(msgLog) > 0;
    }

    @Override
    public boolean updateTryCount(String msgId, Integer tryCount, Date tryTime) {
        Date nextTryTime = JodaTimeUtil.plusMinutes(tryTime, 1);
        MsgLog msgLog = new MsgLog();
        msgLog.setMsgId(msgId);
        msgLog.setTryCount(tryCount);
        msgLog.setNextTryTime(nextTryTime);
        return baseMapper.updateById(msgLog) > 0;
    }
}
